<?php
/* -------------------------------------------------------------------------------------
* 	ID:						$Id: xajax.attribut_manager.php 11 2013-09-21 11:43:11Z phone.mueller@googlemail.com $
* 	Letzter Stand:			$Revision: 11 $
* 	zuletzt geaendert von:	$Author: siekiera $
* 	Datum:					$Date: 2013-09-21 11:43:11 +0000 (Sat, 21 Sep 2013) $
*
* 	SEO:mercari by Siekiera Media
* 	http://www.seo-mercari.de
*
* 	Copyright (c) since 2011 SEO:mercari
* --------------------------------------------------------------------------------------
* 	based on:
* 	(c) 2000-2001 The Exchange Project  (earlier name of osCommerce)
* 	(c) 2002-2003 osCommerce - www.oscommerce.com
* 	(c) 2003     nextcommerce - www.nextcommerce.org
* 	(c) 2005     xt:Commerce - www.xt-commerce.com
*
* 	Released under the GNU General Public License
* ----------------------------------------------------------------------------------- */

require_once(DIR_FS_INC.'inc.get_tax_rate.php');
require_once(DIR_FS_INC.'inc.get_tax_class_id.php');

$xajax->registerFunction('getValue');
$xajax->registerFunction('prepareForm');
$xajax->registerFunction('getForm');
$xajax->registerFunction('saveValues');
$xajax->registerFunction('getOverview');
$xajax->registerFunction('editEntry');
$xajax->registerFunction('deleteEntry');
$xajax->registerFunction('saveNewOption');
$xajax->registerFunction('saveNewValue');
$xajax->registerFunction('preparePrefix');

function getValue($id) {
	global $db;

	$ajax = new xajaxResponse();
	
	$values = $db->db_query("SELECT DISTINCT
								ov.products_options_values_id,
								ov.products_options_values_name
							FROM
								".TABLE_PRODUCTS_OPTIONS_VALUES." ov,
								".TABLE_PRODUCTS_OPTIONS_VALUES_TO_PRODUCTS_OPTIONS." vtpo,
								".TABLE_PRODUCTS_OPTIONS." popt
							WHERE
								ov.language_id = '".(int)$_SESSION['languages_id']."'
							AND
								vtpo.products_options_id = '".(int)$id."'
							AND
							 	ov.products_options_values_id = vtpo.products_options_values_id
							ORDER BY
								ov.products_options_values_name ASC");

	if($values->_numOfRows) {
		$val  = '<select id="value" name="value" onchange="xajax_prepareForm();">';
		$val .= '	<option>-- Wert w&auml;hlen --</option>';
		while(!$values->EOF) {
			$val .= '<option value="'.$values->fields['products_options_values_id'].'">'.$values->fields['products_options_values_name'].'</option>';
			$values->MoveNext();
		}
	}
	
	$ajax->assign('attributes_value', 'innerHTML', $val);
	
	return $ajax;
}

function prepareForm() {
	$ajax = new xajaxResponse();
	
	$js = '	var nh = 450, nw = 520;
			var dlg = $(".ui-dialog");
			var p = dlg.position();
			var l = ($(window).width()-nw)/2;
			var t = ($(window).height()-nh)/2;
			dlg.animate({width:nw,height:nh,left:l,top:t});
			$(".ui-dialog-content").animate({height:(nh-25),width:(nw-20)});
			$("#price_option").fadeIn();';
	
	$ajax->script($js);

	$ajax->call('xajax_getForm');

	return $ajax;
}

function editEntry($aid, $pid){
	$ajax = new xajaxResponse();
	
	$ajax->call('xajax_dialog', draw_form('attribute', 'categories.php', '', 'POST', 'id="attribute_form" onsubmit="return false;"').draw_hidden_field('pID', $pid).draw_hidden_field('aID', $aid).'<table width="100%"><tr><td align="left"><div id="attributes_form"></div></td><td valign="top"><div id="price_option" style="margin-top:11px;"><select id="price_option" name="price_option" onchange="return xajax_preparePrefix(this.value);"><option value="surcharge">+ Preis als Aufschlag</option><option value="total">= Gesamtpreis</option></select></div></td></tr></table></form>', '', 520, 450);
	
	$ajax->call('xajax_getForm', $aid);

	return $ajax;
}

function getForm($aid = '') {
	global $db;
	
	$ajax = new xajaxResponse();
	
	$sort_order = '';
	$model = '';
	$view_type = '';
	$ean = '';
	$stock = '';
	$stock_traffic = '';
	$weight_prefix = '';
	$weight = '';
	$weight_traffic = '';
	$value_price = '';
	$price_prefix = '+';
	
	if(!empty($aid)){
		$attr = $db->db_query("SELECT
	                                attributes_model,
	                                products_attributes_id,
	                                options_values_price,
	                                price_prefix,
	                                products_id,
	                                options_view_type,
	                                attributes_stock,
	                                attributes_stock_status,
	                                attributes_model,
	                                options_values_weight,
	                                options_values_weight_status,
	                                weight_prefix,
	                                attributes_ean,
	                                sortorder
	                             FROM
	                             	".TABLE_PRODUCTS_ATTRIBUTES."
	                             WHERE
	                             	products_attributes_id = '".(int)$aid."'");

	    $sort_order = $attr->fields['sortorder'];
		$model = $attr->fields['attributes_model'];
		$view_type = $attr->fields['options_view_type'];
		$ean = $attr->fields['attributes_ean'];
		$stock = $attr->fields['attributes_stock'];
		$stock_traffic = $attr->fields['attributes_stock_status'];
		$weight_prefix = $attr->fields['weight_prefix'];
		$weight = $attr->fields['options_values_weight'];
		$weight_traffic = $attr->fields['options_values_weight_status'];
		
		require_once(DIR_FS_CATALOG.DIR_WS_CLASSES.'class.price.php');
		$price = new price(DEFAULT_CURRENCY, $_SESSION['customers_status']['customers_status_id'], $db);
		$value_price = $price->AddTax($attr->fields['options_values_price'], get_tax_rate(get_tax_class_id($attr->fields['products_id'])));

		$price_prefix = $attr->fields['price_prefix'];
	}
	
	$prefix[] = array('id' => '+', 'text' => '+');
	$prefix[] = array('id' => '-', 'text' => '-');
	
	$view[] = array('id' => 's', 'text' => 'Selection');
	$view[] = array('id' => 'd', 'text' => 'Dropdown');
	
	$options  = '<table width="100%" style="margin-top:5px" cellpadding="4">';
	
	$options .= '	<tr>';
	$options .= '		<td>Preis - '.(PRICE_IS_BRUTTO == 'true' ? 'Brutto' : 'Netto').':</td>';
	$options .= '		<td>
							'.draw_pull_down_menu('price_prefix', $prefix, $price_prefix, 'style="width:auto" id="price_prefix"').draw_input_field('price', $value_price, 'style="width:103px"').'
						</td>';
	$options .= '	</tr>';
	
	$options .= '	<tr>';
	$options .= '		<td>Darstellung:</td>';
	$options .= '		<td>
							'.draw_pull_down_menu('view_type', $view, $view_type, 'style="width:auto"').'
						</td>';
	$options .= '	</tr>';
	
	$options .= '	<tr>';
	$options .= '		<td>Reihenfolge:</td>';
	$options .= '		<td>
							'.draw_input_field('sort_order', $sort_order).'
						</td>';
	$options .= '	</tr>';
	
	$options .= '	<tr>';
	$options .= '		<td>Artikel-Nr:</td>';
	$options .= '		<td>
							'.draw_input_field('model', $model).'
						</td>';
	$options .= '	</tr>';
	
	$options .= '	<tr>';
	$options .= '		<td>EAN:</td>';
	$options .= '		<td>
							'.draw_input_field('ean', $ean).'
						</td>';
	$options .= '	</tr>';
	
	$options .= '	<tr>';
	$options .= '		<td>Lagerbestand:</td>';
	$options .= '		<td>
							'.draw_input_field('stock', $stock).'
						</td>';
	$options .= '	</tr>';
	
	$options .= '	<tr>';
	$options .= '		<td>Lagerampel anzeigen?:</td>';
	$options .= '		<td>
							'.draw_radio_field_jq('stock_traffic', array(1 => array('1', YES), 0 => array('0', NO)), $stock_traffic || !isset($_GET['pID']) ? '1' : '0').'
						</td>';
	$options .= '	</tr>';
	
	$options .= '	<tr>';
	$options .= '		<td>Gewicht in kg:</td>';
	$options .= '		<td>
							'.draw_pull_down_menu('weight_prefix', $prefix, $weight_prefix, 'style="width:auto"').draw_input_field('weight', $weight, 'style="width:103px"').'
						</td>';
	$options .= '	</tr>';
	
	$options .= '	<tr>';
	$options .= '		<td>Gewicht anzeigen?:</td>';
	$options .= '		<td>
							'.draw_radio_field_jq('weight_traffic', array(1 => array('1', YES), 0 => array('0', NO)), $weight_traffic || !isset($_GET['pID']) ? '1' : '0').'
						</td>';
	$options .= '	</tr>';
	$options .= '	<tr>
						<td colspan="2">&nbsp;</td>
					</tr>';
	$options .= '	<tr>
						<td></td>
						<td>
							<button type="button" class="button" onclick="xajax_saveValues(xajax.getFormValues(\'attribute_form\'), \''.(empty($aid) ? 'insert' : 'update').'\')">'.BUTTON_SAVE.'</button>
						</td>
					</tr>';
	
	$options .= '</table>';
	
	$ajax->assign('attributes_form', 'innerHTML', $options);
	
	$ajax->script('$(function(){$("#stock_traffic").buttonset().fadeIn();});$(function(){$("#weight_traffic").buttonset().fadeIn();})');
	
	return $ajax;
}

function saveValues($val, $action = 'insert') {
	global $db;
	
	$ajax = new xajaxResponse();
	
	require_once(DIR_FS_CATALOG.DIR_WS_CLASSES.'class.price.php');
	$price = new price(DEFAULT_CURRENCY, $_SESSION['customers_status']['customers_status_id'], $db);
		
	if(PRICE_IS_BRUTTO == 'true' && $val['price_option'] == 'surcharge')
	    $value_price = $price->RemoveTax(str_replace(',', '.', $val['price']), get_tax_rate(get_tax_class_id($val['pID'])));

	elseif(PRICE_IS_BRUTTO == 'true' && $val['price_option'] == 'total'){
		$total = $price->GetPrice($val['pID'], false, 1, get_tax_class_id($val['pID']));
		$tmp_value_price = str_replace(',', '.', $val['price'])-$total;	
		
		$value_price = $price->RemoveTax(str_replace(',', '.', $tmp_value_price), get_tax_rate(get_tax_class_id($val['pID'])));
		
	} else
		$value_price = round($val['price'], PRICE_PRECISION);
	
	$sql = array('options_values_price' => $value_price,
				'options_view_type' => $val['view_type'],
				'price_prefix' => $val['price_prefix'],
				'attributes_model' => $val['model'],
				'attributes_stock' => $val['stock'],
				'attributes_stock_status' => $val['stock_traffic'],
				'options_values_weight' => str_replace(',', '.', $val['weight']),
				'options_values_weight_status' => $val['weight_traffic'],
				'weight_prefix' => $val['weight_prefix'],
				'sortorder' => $val['sort_order'],
				'attributes_ean' => $val['ean']);
	
	if($action == 'insert') {
		$sql_addon = array('products_id' => $val['pID'],
							'options_id' => $val['option'],
							'options_values_id' => $val['value']);

		$sql = array_merge($sql, $sql_addon);
		
		$db->db_perform(TABLE_PRODUCTS_ATTRIBUTES, $sql);
		
	} elseif($action == 'update')
		$db->db_perform(TABLE_PRODUCTS_ATTRIBUTES, $sql, 'update', "products_attributes_id = '".$val['aID']."'");
		
	$ajax->script('$(".ui-dialog-content").dialog("close")');
	$ajax->call('xajax_message', 'Die neue Werte wurden gespeichert.', 'success');
	$ajax->call('xajax_getOverview', $val['pID']);
	
	return $ajax;
}

function getOverview($pid) {
	global $db;
	
	$ajax = new xajaxResponse();
	
	$options = $db->db_query("SELECT
									popt.products_options_id,
									popt.products_options_name,
									patrib.products_attributes_id
								FROM
									".TABLE_PRODUCTS_OPTIONS." popt,
									".TABLE_PRODUCTS_ATTRIBUTES." patrib
								WHERE
									patrib.products_id = '".(int)$pid."'
								AND
									patrib.options_id = popt.products_options_id
								AND
									popt.language_id = '".(int)$_SESSION['languages_id']."'
								GROUP BY
									popt.products_options_id
								ORDER BY
									patrib.sortorder");
	
	if($options->_numOfRows) {
		require_once(DIR_FS_CATALOG.DIR_WS_CLASSES.'class.price.php');
		$overview_price = new price(DEFAULT_CURRENCY, $_SESSION['customers_status']['customers_status_id'], $db);
		
		$c = '<br /><div style="text-align:right;font-size:90%;font-style:italic">alle Preise sind '.(PRICE_IS_BRUTTO == 'true' ? 'Brutto' : 'Netto').'</div>';
		
		while(!$options->EOF) {
			$c .= '	<table width="100%" class="dataTable">';
			$c .= '		<tr class="dataTableHeadingRow">';
			$c .= '			<td class="dataTableHeadingContent" width="1"><nobr><u>'.$options->fields['products_options_name'].'</u></nobr></td>';
			$c .= '			<td class="dataTableHeadingContent" width="1">Reihung</td>';
			$c .= '			<td class="dataTableHeadingContent" width="11.1%">Model-Nr</td>';
			$c .= '			<td class="dataTableHeadingContent" width="11.1%">EAN</td>';
			$c .= '			<td class="dataTableHeadingContent" width="11.1%">Lager</td>';
			$c .= '			<td class="dataTableHeadingContent" width="11.1%" align="center">Lager-Ampel</td>';
			$c .= '			<td class="dataTableHeadingContent" width="11.1%"><nobr>Gewicht in kg</nobr></td>';
			$c .= '			<td class="dataTableHeadingContent" width="11.1%">Gewicht-Ampel</td>';
			$c .= '			<td class="dataTableHeadingContent" width="11.1%">Darstellung</td>';
			$c .= '			<td class="dataTableHeadingContent" align="right" width="11.1%">Attr-Preis</td>';
			$c .= '			<td class="dataTableHeadingContent" align="right" width="11.1%">Gesamtpreis</td>';
			$c .= '			<td class="dataTableHeadingContent" width="1"></td>';
			$c .= '		</tr>';
			
			$values = $db->db_query("SELECT
										pov.products_options_values_id,
                                        pov.products_options_values_name,
                                        pa.attributes_model,
                                        pa.options_view_type,
                                        pa.products_attributes_id,
                                        pa.options_values_price,
                                        pa.price_prefix,
                                        pa.attributes_stock,
                                        pa.attributes_stock_status,
                                        pa.attributes_model,
                                        pa.options_values_weight,
                                        pa.options_values_weight_status,
                                        pa.weight_prefix,
                                        pa.attributes_ean,
                                        pa.sortorder
                                     FROM
                                     	".TABLE_PRODUCTS_ATTRIBUTES." pa,
                                        ".TABLE_PRODUCTS_OPTIONS_VALUES." pov
                                     WHERE
                                     	pa.products_id = '".(int)$pid."'
                                     AND
                                     	pa.options_id = '".(int)$options->fields['products_options_id']."'
                                     AND
                                     	pa.options_values_id = pov.products_options_values_id
                                     AND
                                     	pov.language_id = '".(int)$_SESSION['languages_id']."'
                                     ORDER BY
                                     	pa.sortorder");
				
			if($values->_numOfRows) {
				$i = 1;
				while(!$values->EOF) {
					$value_price = '';
					$total = '';
					
					$c .= '		<tr class="'.($i % 2 ? 'attributes-even' : 'attributes-odd').'">';
					$c .= '			<td><strong>'.$values->fields['products_options_values_name'].'</strong></td>';
					$c .= '			<td>'.$values->fields['sortorder'].'</td>';
					$c .= '			<td>'.(!empty($values->fields['attributes_model']) ? $values->fields['attributes_model'] : '-').'</td>';
					$c .= '			<td>'.($values->fields['attributes_ean'] > 0 ? $values->fields['attributes_ean'] : '-').'</td>';
					$c .= '			<td align="center">'.$values->fields['attributes_stock'].'</td>';
					$c .= '			<td>'.($values->fields['attributes_stock_status'] == '1' ? YES : NO).'</td>';
					$c .= '			<td>'.($values->fields['options_values_weight'] > 0 ? number_format($values->fields['options_values_weight'], 2, ',', '.') : '-').'</td>';
					$c .= '			<td>'.($values->fields['options_values_weight_status'] == '1' ? YES : NO).'</td>';
					$c .= '			<td>'.($values->fields['options_view_type'] == 's' ? 'Selection' : 'Dropdown').'</td>';

					if(PRICE_IS_BRUTTO == 'true')
						$value_price = round($values->fields['options_values_price']*((100+(get_tax_rate(get_tax_class_id($pid))))/100), PRICE_PRECISION);
					else
						$value_price = $values->fields['options_values_price'];

					$c .= '			<td align="right">'.$values->fields['price_prefix'].$overview_price->format($value_price, true).'</td>';
					
					$total = $overview_price->GetPrice($pid, false, 1, get_tax_class_id($pid));
								
					if($values->fields['price_prefix'] == '+')
						$total += $value_price;
					else
						$total -= $value_price;
					
					$c .= '			<td align="right">'.$overview_price->format($total, true).'</td>';
					
					$c .= '			<td align="right" width="1">
										<nobr>
											<button class="button" type="button" onclick="xajax_editEntry('.$values->fields['products_attributes_id'].','.$pid.')" style="font-size:160%;padding: 2px 7px 2px 7px;" title="'.BUTTON_EDIT.'">&#9998;</button>
											<button onclick="if(confirm(\'Wollen Sie diesen Eintrag wirklich löschen?\')){xajax_deleteEntry('.$values->fields['products_attributes_id'].','.$pid.')}else{return false}" type="button" class="button" style="font-size:160%;padding: 2px 7px 2px 7px;" title="'.BUTTON_DELETE.'">&#10008;</button>
										</nobr>
									</td>';
					
					$c .= '		</tr>';

					$i++;
					$values->MoveNext();
				}
			}
			$c .= '	</table><br />';
			$options->MoveNext();
		}
	} else {
		$c .= '<em>Es sind noch keine Attribute für dieses Produkt hinterlegt worden.</em>';
	}
	
	$ajax->assign('attributes', 'innerHTML', $c);

	return $ajax;
}

function deleteEntry($aid, $pid) {
	global $db;
	
	$ajax = new xajaxResponse();
	
	$db->db_query("DELETE FROM ".TABLE_PRODUCTS_ATTRIBUTES." WHERE products_attributes_id = '".$aid."'");
	
	$ajax->call('xajax_message', 'Der Eintrag wurde gelöscht', 'warning');
	$ajax->call('xajax_getOverview', $pid);

	return $ajax;
}

function saveNewOption($val) {
	global $db;
	
	$ajax = new xajaxResponse();
	
	$next_id = $db->db_query("SELECT MAX(products_options_id)+1 AS next_id FROM ".TABLE_PRODUCTS_OPTIONS);
	$next = ($next_id->fields['next_id']==0 ? 1 : $next_id->fields['next_id']);
	
	$languages = get_languages();
	for ($i = 0, $n = sizeof($languages); $i < $n; $i ++) {
		$option_name = $val['option_name'][$languages[$i]['id']];
		$option_desc = $val['option_desc'][$languages[$i]['id']];

		$new_option_to_sql = array( 'products_options_id' => $next,
									'products_options_name' => $option_name,
									'products_options_desc' => $option_desc,
									'products_options_image' => '',
									'language_id' => $languages[$i]['id']);

		$db->db_perform(TABLE_PRODUCTS_OPTIONS, $new_option_to_sql);
	}

	$ajax->script('$(".ui-dialog-content").dialog("close")');
	$ajax->call('xajax_message', 'Die neue Option wurde gespeichert, legen Sie dazu nun Optionswerte an', 'success');

	return $ajax;
}

function saveNewValue($val) {
	global $db;
	
	$ajax = new xajaxResponse();
	
	$nid = $db->db_query("SELECT 
								MAX(products_options_values_id)+1 AS next_id 
							FROM 
								".TABLE_PRODUCTS_OPTIONS_VALUES);

	$next = (!empty($nid->fields['next_id']) ? $nid->fields['next_id'] : '1');
	
	$languages = get_languages();
	for($i = 0, $n = sizeof($languages); $i < $n; $i++) {
		$value_name = $val['value_name'][$languages[$i]['id']];
		$value_desc = $val['value_desc'][$languages[$i]['id']];
		$value_hex = $val['hex_image'][$languages[$i]['id']];
		$new_attribut_sql = '';
				
		$new_attribut_sql = array(	'products_options_values_id' => $next,
									'language_id' => $languages[$i]['id'],
									'products_options_values_name' => $value_name,
									'products_options_values_desc' => $value_desc,
									'products_options_hex_image' => $value_hex,
									'products_options_values_image' => '');
		
		$db->db_perform(TABLE_PRODUCTS_OPTIONS_VALUES, $new_attribut_sql);
	}

	$new_value_to_option_sql = array('products_options_id' => $val['option_id'], 
										'products_options_values_id' => $next);

	$db->db_perform(TABLE_PRODUCTS_OPTIONS_VALUES_TO_PRODUCTS_OPTIONS, $new_value_to_option_sql);

	$ajax->script('$(".ui-dialog-content").dialog("close")');
	$ajax->call('xajax_message', 'Der neue Optionswert wurde gespeichert und kann sofort verwendet werden', 'success');

	return $ajax;
}

function preparePrefix($val) {
	$ajax = new xajaxResponse();
	
	if($val == 'total')
		$ajax->assign('price_prefix', 'style.display', 'none');
	elseif($val == 'surcharge')
		$ajax->assign('price_prefix', 'style.display', '');

	return $ajax;
}